package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //1.校验数据
        dto.checkParam();
        //2.查看分页
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //查询
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if(dto.getStatus()!=null){
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> result = page(page, lambdaQueryWrapper);
        //封装
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                result.getTotal(), result.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.检查参数
        if(dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"ID不能为空");
        }
        //2.查询认证用户是否存在
        ApUserRealname apUserRealname = getById(dto.getId());
        if(apUserRealname==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        //判断是否为待审核
        if(!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证信息不是审核状态");
        }
        //根据实名认证关联的userID 查询APUser对象信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if(apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"未发现实名认证信息");
        }
        //更新认证
        apUserRealname.setStatus(status);
        apUserRealname.setReason(dto.getMsg());
        updateById(apUserRealname);
        //4.如果状态为通过
        if(AdminConstants.PASS_AUTH.equals(status)){
            //4.1 创建自媒体账户
            WmUser wmUser = createWmUser(dto,apUser);
            //4.2 创建作者信息
            createApAuthor(wmUser,apUser);
        }

        //返回结果
        return ResponseResult.okResult();

    }

    @Autowired
    ArticleFeign articleFeign;
    //远程创建作者信息
    private void createApAuthor(WmUser wmUser, ApUser apUser) {
        //1.先根据apUserId远程查询作者信息
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if(!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //2. 判读是否存在
        ApAuthor apAuthor = result.getData();


        if(apAuthor!=null){
            //3. 存在，作者已存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"自媒体用户已经存在，创建失败");
        }

        //4.不存在，创建
        apAuthor=new ApAuthor();

        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        //5. 远程保存
        articleFeign.save(apAuthor);

    }


    @Autowired
    WemediaFeign wemediaFeign;

    //远程开通自媒体账户
    private WmUser createWmUser(AuthDTO dto, ApUser apUser) {
        //1. 根据用户 远程查询自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();


        //2.如果有该用户，抛出异常 自媒体用户已存在
        if(wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体用户已经存在，开通失败");
        }
        //3.如果没该用户，创建
        wmUser=new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        
        //4.远程保存自媒体用户
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(!saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return saveResult.getData();

    }
}
